﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;

namespace AirLinq.Reflection {
	public static class ReflectionHelper {
		public static MethodInfo GetBodyMethod<T>(Expression<Func<T>> expression) {
			if (expression.Body.NodeType != ExpressionType.Call) {
				throw new ArgumentException("expression must be Call type");
			}
			var callExpression = (MethodCallExpression)expression.Body;
			var res = callExpression.Method;
			if (res.IsGenericMethod) {
				res = res.GetGenericMethodDefinition();
			}
			return res;
		}
		public static MethodInfo GetBodyMethod<T,TRes>(Expression<Func<T,TRes>> expression) {
			if (expression.Body.NodeType != ExpressionType.Call) {
				throw new ArgumentException("expression must be Call type");
			}
			var callExpression = (MethodCallExpression)expression.Body;
			var res = callExpression.Method;
			if (res.IsGenericMethod) {
				res = res.GetGenericMethodDefinition();
			}
			return res;
		}
		public static ConstructorInfo GetBodyConstructor<T>(Expression<Func<T>> expression) {
			if (expression.Body.NodeType != ExpressionType.New) {
				throw new ArgumentException("expression must be New type");
			}
			var newExpression = (NewExpression)expression.Body;
			return newExpression.Constructor;
		}
	}
}
